import React, { useState } from 'react'
import { 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  InputNumber,
  Card,
  Statistic,
  Row,
  Col,
  Tooltip
} from 'antd'
import { 
  PlusOutlined, 
  DeleteOutlined, 
  EyeOutlined,
  DatabaseOutlined
} from '@ant-design/icons'
import { useQuery } from '@tanstack/react-query'
import { api } from '../services/api'

const Topics: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [recordsModalVisible, setRecordsModalVisible] = useState(false)
  const [selectedTopic, setSelectedTopic] = useState<string>('')
  const [form] = Form.useForm()

  const { data: topics, isLoading, refetch } = useQuery({
    queryKey: ['topics'],
    queryFn: api.getTopics,
  })

  const { data: topicRecords } = useQuery({
    queryKey: ['topicRecords', selectedTopic],
    queryFn: () => api.getTopicRecords(selectedTopic),
    enabled: !!selectedTopic && recordsModalVisible,
  })

  const columns = [
    {
      title: '主题名称',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => (
        <Space>
          <DatabaseOutlined style={{ color: '#1890ff' }} />
          {name}
        </Space>
      ),
    },
    {
      title: '分区数',
      dataIndex: 'partitions',
      key: 'partitions',
    },
    {
      title: '副本因子',
      dataIndex: 'replication_factor',
      key: 'replication_factor',
    },
    {
      title: '记录数',
      dataIndex: 'record_count',
      key: 'record_count',
      render: (count: number) => count?.toLocaleString() || '0',
    },
    {
      title: '大小',
      dataIndex: 'size_bytes',
      key: 'size_bytes',
      render: (bytes: number) => {
        if (bytes < 1024) return `${bytes} B`
        if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
        if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`
        return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Tooltip title="查看记录">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handleViewRecords(record.name)}
            />
          </Tooltip>
          <Tooltip title="删除主题">
            <Button 
              type="text" 
              danger 
              icon={<DeleteOutlined />} 
              onClick={() => handleDeleteTopic(record.name)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ]

  const recordColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
    },
    {
      title: '分区',
      dataIndex: 'partition',
      key: 'partition',
    },
    {
      title: '偏移量',
      dataIndex: 'offset',
      key: 'offset',
    },
    {
      title: '时间戳',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (date: string) => new Date(date).toLocaleString('zh-CN'),
    },
    {
      title: '数据',
      dataIndex: 'data',
      key: 'data',
      render: (data: any) => (
        <pre style={{ margin: 0, maxWidth: 300, overflow: 'auto' }}>
          {JSON.stringify(data, null, 2)}
        </pre>
      ),
    },
  ]

  const handleCreateTopic = () => {
    setIsModalVisible(true)
    form.resetFields()
  }

  const handleDeleteTopic = (name: string) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除主题 "${name}" 吗？此操作不可撤销，所有数据将丢失。`,
      onOk: async () => {
        try {
          await api.deleteTopic(name)
          refetch()
        } catch (error) {
          console.error('删除主题失败:', error)
        }
      },
    })
  }

  const handleViewRecords = (topicName: string) => {
    setSelectedTopic(topicName)
    setRecordsModalVisible(true)
  }

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields()
      await api.createTopic(values)
      setIsModalVisible(false)
      refetch()
    } catch (error) {
      console.error('创建主题失败:', error)
    }
  }

  // 计算统计数据
  const stats = topics?.reduce((acc: any, topic: any) => {
    acc.totalTopics += 1
    acc.totalRecords += topic.record_count || 0
    acc.totalSize += topic.size_bytes || 0
    acc.totalPartitions += topic.partitions || 0
    return acc
  }, { totalTopics: 0, totalRecords: 0, totalSize: 0, totalPartitions: 0 }) || {}

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <h1>Fluvio主题管理</h1>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleCreateTopic}
        >
          创建主题
        </Button>
      </div>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="主题总数"
              value={stats.totalTopics}
              prefix={<DatabaseOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总记录数"
              value={stats.totalRecords}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总分区数"
              value={stats.totalPartitions}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="存储大小"
              value={stats.totalSize}
              formatter={(value) => {
                const bytes = Number(value)
                if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
                if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`
                return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`
              }}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      <Table 
        columns={columns} 
        dataSource={topics} 
        loading={isLoading}
        rowKey="name"
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 个主题`,
        }}
      />

      {/* 创建主题模态框 */}
      <Modal
        title="创建Fluvio主题"
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={500}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="主题名称"
            rules={[
              { required: true, message: '请输入主题名称' },
              { pattern: /^[a-zA-Z0-9_-]+$/, message: '主题名称只能包含字母、数字、下划线和连字符' }
            ]}
          >
            <Input placeholder="输入主题名称" />
          </Form.Item>

          <Form.Item
            name="partitions"
            label="分区数"
            rules={[{ required: true, message: '请输入分区数' }]}
            initialValue={1}
          >
            <InputNumber min={1} max={100} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="replication_factor"
            label="副本因子"
            rules={[{ required: true, message: '请输入副本因子' }]}
            initialValue={1}
          >
            <InputNumber min={1} max={10} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="retention_time"
            label="保留时间 (秒)"
            help="数据保留时间，留空表示永久保留"
          >
            <InputNumber min={1} style={{ width: '100%' }} placeholder="例如: 86400 (1天)" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 查看记录模态框 */}
      <Modal
        title={`主题记录: ${selectedTopic}`}
        open={recordsModalVisible}
        onCancel={() => setRecordsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Table 
          columns={recordColumns} 
          dataSource={topicRecords} 
          rowKey="id"
          size="small"
          pagination={{ pageSize: 5 }}
        />
      </Modal>
    </div>
  )
}

export default Topics
